﻿#include "CExportResultTh.h"
#include "Public.h"
#include "CSqlOper.h"
#include "CPdfRptInterface.h"
#include "CGlobal.h"

CExportResultTh::CExportResultTh()
{
	m_pMutex = new QMutex(QMutex::Recursive);
	m_bhread.store(false);
	m_bShouldStop = false;
	m_bFrist = true;
	m_bFindLastResultTime = false;
	m_nCount = 0;
	m_pPdfRptInterface = new CPdfRptInterface();
}

CExportResultTh::~CExportResultTh()
{
	// 先请求停止线程
	m_bShouldStop = true;

	// 然后等待线程结束
	quit();
	wait();
	if (m_pMutex != nullptr)
	{
		delete m_pMutex;
		m_pMutex = nullptr;
	}
	if (m_pPdfRptInterface != nullptr)
	{
		delete m_pPdfRptInterface;
		m_pPdfRptInterface = nullptr;
	}
}

void CExportResultTh::ThreadStart()
{
	QMutexLocker locker(m_pMutex);
	if (!m_bhread.load())
	{
		if (m_bFrist)
		{
			start();
			m_bFrist = false;
		}
		m_bhread.store(true);
	}
}

void CExportResultTh::ThreadStop()
{
	QMutexLocker locker(m_pMutex);
	if (m_bhread.load())
	{
		m_bhread.store(false);
	}
}

void CExportResultTh::run()
{
	while (!m_bShouldStop)
	{
		// 使用更精细的锁控制，避免长时间持有锁
		{
			QMutexLocker locker(m_pMutex);
			if (!m_bhread.load())
			{
				sysSleep(1000);
				continue;
			}

			if (m_bFindLastResultTime == false)
			{
				QString sErrMsg = "";
				QVector<QSqlRecord> vecInfo;
				bool bRet = CSqlOper::instance().selectResultLastTime(vecInfo, sErrMsg);
				if (bRet)
				{
					if (vecInfo.size() > 0)
					{
						for (int i = 0; i < vecInfo.size(); i++)
						{
							m_dLastResultTime = vecInfo[i].value("latest_time").toDateTime();
							QString sTime = m_dLastResultTime.toString("yyyy/MM/dd hh:mm:ss");
							int a = 0;
						}
					}
					else if (vecInfo.size() == 0)
					{
						m_dLastResultTime = QDateTime::currentDateTime();
					}
					m_bFindLastResultTime = true;
				}
				else
				{
					m_bFindLastResultTime = false;
				}
			}
		} // 锁在这里释放，避免长时间持有

		// 处理计数和报告生成（不需要一直持有锁）
		if (m_nCount >= 5) // 1分钟查看一下当前是否需要输出报告
		{
			QDateTime currentTime = QDateTime::currentDateTime();
			if (qAbs(currentTime.secsTo(m_dLastResultTime)) > g_nResultTime)
			{
				m_pPdfRptInterface->expCorrectPdfRpt(g_sResultPath, g_sHttpUrl, g_sCustomName,
					m_dLastResultTime, currentTime);

				QMutexLocker locker(m_pMutex);
				m_dLastResultTime = currentTime;
			}

			QMutexLocker locker(m_pMutex);
			m_nCount = 0;
		}
		else
		{
			QMutexLocker locker(m_pMutex);
			m_nCount++;
		}

		sysSleep(1000);
	}
}
